package com.pc.tas.learning.trace;

import com.pc.cloud.message.MessageServices;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.json.JSONException;

import javax.servlet.http.HttpServletRequest;

public class TraceManager {
	public TraceManager() {
		super();
	}
	
	public static void send(Trace trace) throws Exception {
		try {
			MessageServices.messageManager.sendMessage(TraceListener.QUEUE_NAME,trace.toJSON());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public static Trace getTrace(HttpServletRequest request) throws Exception {
		Trace trace = new Trace();
		String ip = request.getHeader("remote_addr");
		if(ip == null || "".equals(ip.trim())){
			ip = request.getRemoteAddr();
			if("0:0:0:0:0:0:0:1".equals(ip)){
				ip = "127.0.0.1";
			}
		}
        String referrer = request.getHeader("referer");
        String userAgent = request.getHeader("User-Agent"); 
        String url = referrer;
        String rr = request.getParameter("rr");
        String realReferrer = null;
        if(rr != null){
        	realReferrer = java.net.URLDecoder.decode(rr,"utf-8");
        }
        String clientId = request.getParameter("clientId");
        if("\"\"".equals(clientId)){
        	clientId = "0";
        }
        String pageId = request.getParameter("pageId");
        
        trace.setPageId(Long.parseLong(pageId));
        trace.setIP(ip);
        trace.setReferer(realReferrer);
        trace.setUserAgent(userAgent);
        trace.setUrl(url);
        trace.setClientId(clientId);
        
        String payload = java.net.URLDecoder.decode(request.getParameter("pageId"),"utf-8");
     //   System.out.println("payload:" + payload);
        
        if(payload == null || payload.trim().length()== 0) {
        	throw new Exception("payload is null!");
        }
        trace.setPayload(payload);       
		return trace;
	}	
}
